summary refs log tree commit diff stats
path: root/compiler/strutils2.nim
blob: f44b811c75adae7ee999fe985341ab8a4bfce816 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
##[
internal API for now, subject to modifications and moving around

string API's focusing on performance, that can be used as building blocks
for other routines.

Un-necessary allocations are avoided and appropriate algorithms are used at the
expense of code clarity when justified.
]##

proc dataPointer*[T](a: T): pointer =
  ## same as C++ `data` that works with std::string, std::vector etc.
  ## Note: safe to use when a.len == 0 but whether the result is nil or not
  ## is implementation defined for performance reasons.
  # this could be improved with ocmpiler support to avoid the `if`, e.g. in C++
  # `&a[0]` is well defined even if a.size() == 0
  when T is string | seq:
    if a.len == 0: nil else: cast[pointer](a[0].unsafeAddr)
  elif T is array:
    when a.len > 0: a.unsafeAddr
    else: nil
  elif T is cstring:
    cast[pointer](a)
  else: static: doAssert false, $T

proc setLen*(result: var string, n: int, isInit: bool) =
  ## when isInit = false, elements are left uninitialized, analog to `{.noinit.}`
  ## else, there are 0-initialized.
  # xxx placeholder until system.setLen supports this
  # to distinguish between algorithms that need 0-initialization vs not; note
  # that `setLen` for string is inconsistent with `setLen` for seq.
  # likwise with `newString` vs `newSeq`. This should be fixed in `system`.
  let n0 = result.len
  result.setLen(n)
  if isInit and n > n0:
    zeroMem(result[n0].addr, n - n0)

proc forceCopy*(result: var string, a: string) =
  ## also forces a copy if `a` is shallow
  # the naitve `result = a` would not work if `a` is shallow
  let n = a.len
  result.setLen n, isInit = false
  copyMem(result.dataPointer, a.dataPointer, n)

proc isUpperAscii(c: char): bool {.inline.} =
  # avoids import strutils.isUpperAscii
  c in {'A'..'Z'}

proc toLowerAscii*(a: var string) =
  ## optimized and inplace overload of strutils.toLowerAscii
  # refs https://github.com/timotheecour/Nim/pull/54
  # this is 10X faster than a naive implementation using a an optimization trick
  # that can be adapted in similar contexts. Predictable writes avoid write
  # hazards and lead to better machine code, compared to random writes arising
  # from: `if c.isUpperAscii: c = ...`
  for c in mitems(a):
    c = chr(c.ord + (if c.isUpperAscii: (ord('a') - ord('A')) else: 0))
vabit.com> 2010-01-01 16:38:41 +0100 draw a list of bookmarks when pressing ` or '' href='/akspecs/ranger/commit/ranger/container/bookmarks.py?id=08f21ae5ad8d92d3f1819a95db3e5bdce603f4da'>08f21ae5 ^
f2d8598d ^


291ca616 ^

f2d8598d ^


7d6389d6 ^
f2d8598d ^


b4b0eb24 ^


291ca616 ^

f2d8598d ^






f6910552 ^

f2d8598d ^
b4b0eb24 ^

ea87d005 ^
f6910552 ^
f2d8598d ^
d955e3f0 ^
f6910552 ^



0a1bc759 ^
f6910552 ^



ea87d005 ^
f6910552 ^



ea87d005 ^
f6910552 ^




0a1bc759 ^
f6910552 ^
0a1bc759 ^
f6910552 ^

0a1bc759 ^
f6910552 ^
0a1bc759 ^
f6910552 ^
d955e3f0 ^
6874e0ea ^

f2d8598d ^
b4b0eb24 ^
6874e0ea ^
f6910552 ^
0128bee7 ^

6874e0ea ^

6874e0ea ^

6874e0ea ^



f2d8598d ^




0128bee7 ^



501f5014 ^
75013dc7 ^



501f5014 ^

f2d8598d ^










ea87d005 ^
d955e3f0 ^



f2d8598d ^

d955e3f0 ^
f2d8598d ^



0128bee7 ^

f2d8598d ^



ea87d005 ^
f2d8598d ^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
                                                                 
 



                                                                      
 






                                                                       
 



                                                          
 
                        
                                                                         
 
                                                                              
 


                                                                                     
 

                                                                                   


                         
                                                


                                                                           

                                       



                                                

                       
                                                            
                    
                                                    


                               
                                                           
 
                              
                                                            

                                 

                                         



                                                         

                                                                     










                                                              
                                                    

                                             
 

                                             


                                                              

                                 


                                            
                                                               


                                                     


                                                                                       

                                 






                                                            

                         
                                                               

                                                                                     
 
                    
                                                     
                                                         



                                                                        
                                            



                                                       
 



                                                                  
 




                                                     
                                                              
                                                                   
                                                                                             

                                               
                                                                              
                             
                                                                                    
 
                                                                  

                       
                                                          
                                                                                           
                         
                             

                                     

                                                 

                                                           



                                                                                         




                                    



                                     
                                                 



                                                                           

                                 










                                                                                   
 



                                           

                                    
                                             



                                    

                                     



                                                          
 

                                                   
# Copyright (C) 2009, 2010  Roman Zimbelmann <romanz@lavabit.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import string
import re
import os
ALLOWED_KEYS = string.ascii_letters + string.digits + "`'"

class Bookmarks(object):
	"""Bookmarks is a container which associates keys with bookmarks.

		A key is a string with: len(key) == 1 and key in ALLOWED_KEYS.

		A bookmark is an object with: bookmark == bookmarktype(str(instance))
		Which is true for str or FileSystemObject. This condition is required
		so bookmark-objects can be saved to and loaded from a file.

		Optionally, a bookmark.go() method is used for entering a bookmark.
		"""

	last_mtime = None
	autosave = True
	load_pattern = re.compile(r"^[\d\w']:.")

	def __init__(self, bookmarkfile, bookmarktype=str, autosave=False):
		"""<bookmarkfile> specifies the path to the file where
		bookmarks are saved in.
		"""
		self.autosave = autosave
		self.dct = {}
		self.path = bookmarkfile
		self.bookmarktype = bookmarktype

	def load(self):
		"""Load the bookmarks from path/bookmarks"""
		try:
			new_dict = self._load_dict()
		except OSError:
			return

		self._set_dict(new_dict, original=new_dict)

	def delete(self, key):
		"""Delete the bookmark with the given key"""
		if key == '`':
			key = "'"
		if key in self.dct:
			del self.dct[key]
			if self.autosave: self.save()

	def enter(self, key):
		"""Enter the bookmark with the given key.
		Requires the bookmark instance to have a go() method.
		"""

		try:
			return self[key].go()
		except (IndexError, KeyError, AttributeError):
			return False

	def update_if_outdated(self):
		if self.last_mtime != self._get_mtime():
			self.update()

	def remember(self, value):
		"""Bookmarks <value> to the key '"""
		self["'"] = value
		if self.autosave: self.save()

	def __iter__(self):
		return iter(self.dct.items())

	def __getitem__(self, key):
		"""Get the bookmark associated with the key"""
		if key == '`':
			key = "'"
		if key in self.dct:
			return self.dct[key]
		else:
			raise KeyError("Nonexistant Bookmark!")

	def __setitem__(self, key, value):
		"""Bookmark <value> to the key <key>.
		key is expected to be a 1-character string and element of ALLOWED_KEYS.
		value is expected to be a filesystemobject.
		"""
		if key == '`':
			key = "'"
		if key in ALLOWED_KEYS:
			self.dct[key] = value
			if self.autosave: self.save()

	def __contains__(self, key):
		"""Test whether a bookmark-key is defined"""
		return key in self.dct

	def update(self):
		"""Update the bookmarks from the bookmark file.
		Useful if two instances are running which define different bookmarks.
		"""

		try:
			real_dict = self._load_dict()
			real_dict_copy = real_dict.copy()
		except OSError:
			return

		for key in set(self.dct.keys()) | set(real_dict.keys()):
			# set some variables
			if key in self.dct:
				current = self.dct[key]
			else:
				current = None

			if key in self.original_dict:
				original = self.original_dict[key]
			else:
				original = None

			if key in real_dict:
				real = real_dict[key]
			else:
				real = None

			# determine if there have been changes
			if current == original and current != real:
				continue   # another ranger instance has changed the bookmark

			if key not in self.dct:
				del real_dict[key]   # the user has deleted it
			else:
				real_dict[key] = current   # the user has changed it

		self._set_dict(real_dict, original=real_dict_copy)

	def save(self):
		"""Save the bookmarks to the bookmarkfile.
		This is done automatically after every modification if autosave is True."""
		import os
		self.update()
		if self.path is None:
			return
		if os.access(self.path, os.W_OK):
			f = open(self.path, 'w')
			for key, value in self.dct.items():
				if type(key) == str\
						and key in ALLOWED_KEYS:
					f.write("{0}:{1}\n".format(str(key), str(value)))

			f.close()
		self._update_mtime()

	def _load_dict(self):
		import os
		dct = {}

		if self.path is None:
			return dct

		if not os.path.exists(self.path):
			try:
				f = open(self.path, 'w')
			except:
				raise OSError('Cannot read the given path')
			f.close()

		if os.access(self.path, os.R_OK):
			f = open(self.path, 'r')
			for line in f:
				if self.load_pattern.match(line):
					key, value = line[0], line[2:-1]
					if key in ALLOWED_KEYS: 
						dct[key] = self.bookmarktype(value)
			f.close()
			return dct
		else:
			raise OSError('Cannot read the given path')

	def _set_dict(self, dct, original):
		if original is None:
			original = {}

		self.dct.clear()
		self.dct.update(dct)
		self.original_dict = original
		self._update_mtime()

	def _get_mtime(self):
		import os
		if self.path is None:
			return None
		try:
			return os.stat(self.path).st_mtime
		except OSError:
			return None

	def _update_mtime(self):
		self.last_mtime = self._get_mtime()