Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SQLChars.cs « SQLTypes « Data « System « System.Data « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4fc5106f14c019e2fb038bdb70279efbadda1318 (plain)
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//------------------------------------------------------------------------------
// <copyright file="SqlChars.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
//  </copyright>																
// <owner current="true" primary="true">junfang</owner>
// <owner current="true" primary="false">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------

//**************************************************************************
// @File: SqlChars.cs
// @Owner: junfang
//
// Created by:	JunFang
//
// Description: Class SqlChars is used to represent a char/varchar/nchar/nvarchar
//		data from SQL Server. It contains a char array buffer, which can
//		be refilled. For example, in data access, user could use one instance
//		of SqlChars to bind to a binary column, and we will just keep copying
//		the data into the same instance, and avoid allocation per row.
//
// Notes: 
//	
// History:
//
//     @Version: Yukon
//     120214 JXF  09/23/02 SqlBytes/SqlChars class indexer
//     112296 AZA  07/06/02 Seal SqlAccess classes.
//     107151 AZA  04/18/02 Track byte array buffer as well as SqlBytes in 
//                          sqlaccess.
//     107216 JXF  04/17/02 











namespace System.Data.SqlTypes {
	using System;
	using System.IO;
	using System.Runtime.InteropServices;
	using System.Diagnostics;
	using System.Data.Common;
	using System.Data.Sql;
    using System.Data.SqlClient;
	using System.Data.SqlTypes;
	using System.Xml;
	using System.Xml.Schema;
	using System.Xml.Serialization;
	using System.Runtime.Serialization;
	using System.Security.Permissions;

	[Serializable,XmlSchemaProvider("GetXsdType")]
    public sealed class SqlChars : System.Data.SqlTypes.INullable, IXmlSerializable, ISerializable {
		// --------------------------------------------------------------
		//	  Data members
		// --------------------------------------------------------------

		// SqlChars has five possible states
		// 1) SqlChars is Null
		//		- m_stream must be null, m_lCuLen must be x_lNull
		// 2) SqlChars contains a valid buffer, 
		//		- m_rgchBuf must not be null, and m_stream must be null
		// 3) SqlChars contains a valid pointer
		//		- m_rgchBuf could be null or not,
		//			if not null, content is garbage, should never look into it.
		//      - m_stream must be null.
		// 4) SqlChars contains a SqlStreamChars
		//      - m_stream must not be null
		//      - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it.
		//		- m_lCurLen must be x_lNull.
		// 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed)
		//
		internal char[]	            m_rgchBuf;	// Data buffer
		private  long	            m_lCurLen;	// Current data length
		internal SqlStreamChars     m_stream;
		private  SqlBytesCharsState m_state;

		private  char[]	            m_rgchWorkBuf;	// A 1-char work buffer.

		// The max data length that we support at this time.
		private const long x_lMaxLen = (long)System.Int32.MaxValue;

		private const long x_lNull = -1L;

		// --------------------------------------------------------------
		//	  Constructor(s)
		// --------------------------------------------------------------

		// Public default constructor used for XML serialization
		public SqlChars() {
			SetNull();
		}

		// Create a SqlChars with an in-memory buffer
		public SqlChars(char[] buffer) {
			m_rgchBuf = buffer;
			m_stream = null;
			if (m_rgchBuf == null) {
				m_state = SqlBytesCharsState.Null;
				m_lCurLen = x_lNull;
            }
			else {
				m_state = SqlBytesCharsState.Buffer;
				m_lCurLen = (long)m_rgchBuf.Length;
            }

			m_rgchWorkBuf = null;

			AssertValid();
        }

	// Create a SqlChars from a SqlString
	public SqlChars(SqlString value) : this (value.IsNull ? (char[])null : value.Value.ToCharArray()) {
        }

		// Create a SqlChars from a SqlStreamChars
		internal SqlChars(SqlStreamChars s) {
			m_rgchBuf = null;
			m_lCurLen = x_lNull;
			m_stream = s;
			m_state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;

			m_rgchWorkBuf = null;

			AssertValid();
        }

		// Constructor required for serialization. Deserializes as a Buffer. If the bits have been tampered with
		// then this will throw a SerializationException or a InvalidCastException.
		private SqlChars(SerializationInfo info, StreamingContext context)
			{
			m_stream = null;
			m_rgchWorkBuf = null;

			if (info.GetBoolean("IsNull"))
				{
				m_state = SqlBytesCharsState.Null;
				m_rgchBuf = null;
				}
			else
				{
				m_state = SqlBytesCharsState.Buffer;
				m_rgchBuf = (char[]) info.GetValue("data", typeof(char[]));
				m_lCurLen = m_rgchBuf.Length;
				}

			AssertValid();
			}

		// --------------------------------------------------------------
		//	  Public properties
		// --------------------------------------------------------------

		// INullable
		public bool IsNull {
			get {
			    return m_state == SqlBytesCharsState.Null;
			}
		}

		// Property: the in-memory buffer of SqlChars
		//		Return Buffer even if SqlChars is Null.

		public char[] Buffer {
			get {
				if (FStream())	{
					CopyStreamToBuffer();
                }
				return m_rgchBuf;
            }
        }

		// Property: the actual length of the data
		public long Length {
			get {
				switch (m_state) {
					case SqlBytesCharsState.Null: 
                        throw new SqlNullValueException();

					case SqlBytesCharsState.Stream:
                        return m_stream.Length;

					default:
						return m_lCurLen;
                }
            }
        }

		// Property: the max length of the data
		//		Return MaxLength even if SqlChars is Null.
		//		When the buffer is also null, return -1.
		//		If containing a Stream, return -1.

		public long MaxLength {
			get {
				switch (m_state) {
					case SqlBytesCharsState.Stream:
						return -1L;

					default:
						return (m_rgchBuf == null) ? -1L : (long)m_rgchBuf.Length;
                }
            }
        }

		// Property: get a copy of the data in a new char[] array.

		public char[] Value {
			get {
                char[] buffer;

				switch (m_state) {
					case SqlBytesCharsState.Null: 
						throw new SqlNullValueException();

					case SqlBytesCharsState.Stream:
						if (m_stream.Length > x_lMaxLen)
                                            throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage));
						buffer = new char[m_stream.Length];
						if (m_stream.Position != 0)
							m_stream.Seek(0, SeekOrigin.Begin);
						m_stream.Read(buffer, 0, checked((int)m_stream.Length));
						break;

					default:
						buffer = new char[m_lCurLen];
						Array.Copy(m_rgchBuf, buffer, (int)m_lCurLen);
						break;
                }

				return buffer;
            }
        }

		// class indexer

		public char this[long offset] {
			get {
                if (offset < 0 || offset >= this.Length)
                    throw new ArgumentOutOfRangeException("offset");

                if (m_rgchWorkBuf == null)
					m_rgchWorkBuf = new char[1];

				Read(offset, m_rgchWorkBuf, 0, 1);
				return m_rgchWorkBuf[0];
            }
			set {
				if (m_rgchWorkBuf == null)
					m_rgchWorkBuf = new char[1];
				m_rgchWorkBuf[0] = value;
				Write(offset, m_rgchWorkBuf, 0, 1);
            }
        }

        internal SqlStreamChars Stream {
            get {
                return FStream() ? m_stream : new StreamOnSqlChars(this);
            }
            set {
                m_lCurLen = x_lNull;
                m_stream = value;
                m_state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;

                AssertValid();                   
            }
        }

	    public StorageState Storage {
        	get {
        		switch (m_state) {
        			case SqlBytesCharsState.Null: 
        				throw new SqlNullValueException();

        			case SqlBytesCharsState.Stream:
        			    return StorageState.Stream;

        			case SqlBytesCharsState.Buffer:
        			    return StorageState.Buffer;

        			default:
        			    return StorageState.UnmanagedBuffer;
                }
            }
        }

		// --------------------------------------------------------------
		//	  Public methods
		// --------------------------------------------------------------

		public void SetNull() {
    		m_lCurLen = x_lNull;
    		m_stream = null;
    		m_state = SqlBytesCharsState.Null;

    		AssertValid();
		}

		// Set the current length of the data
		// If the SqlChars is Null, setLength will make it non-Null.
		public void SetLength(long value) {
			if (value < 0)
				throw new ArgumentOutOfRangeException("value");

			if (FStream()) {
				m_stream.SetLength(value);
            }
			else {
				// If there is a buffer, even the value of SqlChars is Null,
				// still allow setting length to zero, which will make it not Null.
				// If the buffer is null, raise exception
				//
				if (null == m_rgchBuf)
                    throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage));

				if (value > (long)m_rgchBuf.Length)
					throw new ArgumentOutOfRangeException("value");

				else if (IsNull)
					// At this point we know that value is small enough
					// Go back in buffer mode
					m_state = SqlBytesCharsState.Buffer;
                                
				m_lCurLen = value;
				}

			AssertValid();
        }

		// Read data of specified length from specified offset into a buffer

		public long Read(long offset, char[] buffer, int offsetInBuffer, int count) {
			if (IsNull)
                throw new SqlNullValueException();

			// Validate the arguments
			if (buffer == null)
				throw new ArgumentNullException("buffer");

			if (offset > this.Length || offset < 0)
				throw new ArgumentOutOfRangeException("offset");

			if (offsetInBuffer > buffer.Length || offsetInBuffer < 0)
				throw new ArgumentOutOfRangeException("offsetInBuffer");

			if (count < 0 || count > buffer.Length - offsetInBuffer)
				throw new ArgumentOutOfRangeException("count");

			// Adjust count based on data length
			if (count > this.Length - offset)
				count = (int)(this.Length - offset);

			if (count != 0)	{
				switch (m_state) {
					case SqlBytesCharsState.Stream:
					    if (m_stream.Position != offset)
							m_stream.Seek(offset, SeekOrigin.Begin);
						m_stream.Read(buffer, offsetInBuffer, count);
						break;

					default:
						Array.Copy(m_rgchBuf, offset, buffer, offsetInBuffer, count);
						break;
                }
            }
			return count;
        }

		// Write data of specified length into the SqlChars from specified offset

		public void Write(long offset, char[] buffer, int offsetInBuffer, int count) {
			if (FStream()) {
				if (m_stream.Position != offset)
					m_stream.Seek(offset, SeekOrigin.Begin);
				m_stream.Write(buffer, offsetInBuffer, count);
            }
			else {
				// Validate the arguments
				if (buffer == null)
					throw new ArgumentNullException("buffer");

				if (m_rgchBuf == null)
                    throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage));

				if (offset < 0)
					throw new ArgumentOutOfRangeException("offset");
				if (offset > m_rgchBuf.Length)
                    throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage));

				if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length)
					throw new ArgumentOutOfRangeException("offsetInBuffer");

				if (count < 0 || count > buffer.Length - offsetInBuffer)
					throw new ArgumentOutOfRangeException("count");

				if (count > m_rgchBuf.Length - offset)
                    throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage));

				if (IsNull) {
					// If NULL and there is buffer inside, we only allow writing from 
					// offset zero.
					//
					if (offset != 0)
                        throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteNonZeroOffsetOnNullMessage));

					// treat as if our current length is zero.
					// Note this has to be done after all inputs are validated, so that
					// we won't throw exception after this point.
					//
					m_lCurLen = 0;
                    m_state = SqlBytesCharsState.Buffer;
                }
				else if (offset > m_lCurLen) {
					// Don't allow writing from an offset that this larger than current length.
					// It would leave uninitialized data in the buffer.
					//
                    throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage));
				}

				if (count != 0)	{
					Array.Copy(buffer, offsetInBuffer, m_rgchBuf, offset, count);

					// If the last position that has been written is after
					// the current data length, reset the length
					if (m_lCurLen < offset + count)
						m_lCurLen = offset + count;
                }
            }

			AssertValid();
        }

		public SqlString ToSqlString() {
			return IsNull ? SqlString.Null : new String(Value);
        }

		// --------------------------------------------------------------
		//	  Conversion operators
		// --------------------------------------------------------------

		// Alternative method: ToSqlString()
		public static explicit operator SqlString(SqlChars value) {
			return value.ToSqlString();
		}

		// Alternative method: constructor SqlChars(SqlString)
		public static explicit operator SqlChars(SqlString value) {
			return new SqlChars(value);
		}

		// --------------------------------------------------------------
		//	  Private utility functions
		// --------------------------------------------------------------

		[System.Diagnostics.Conditional("DEBUG")] 
		private void AssertValid() {
			Debug.Assert(m_state >= SqlBytesCharsState.Null && m_state <= SqlBytesCharsState.Stream);

			if (IsNull)	{
            }
			else {
				Debug.Assert((m_lCurLen >= 0 && m_lCurLen <= x_lMaxLen) || FStream());
				Debug.Assert(FStream() || (m_rgchBuf != null && m_lCurLen <= m_rgchBuf.Length));
				Debug.Assert(!FStream() || (m_lCurLen == x_lNull));
			}
			Debug.Assert(m_rgchWorkBuf == null || m_rgchWorkBuf.Length == 1);
		}

		// whether the SqlChars contains a Stream
		internal bool FStream() {
			return m_state == SqlBytesCharsState.Stream;
        }

		// Copy the data from the Stream to the array buffer.
		// If the SqlChars doesn't hold a buffer or the buffer
		// is not big enough, allocate new char array.
		private void CopyStreamToBuffer() {
			Debug.Assert(FStream());

			long lStreamLen = m_stream.Length;
			if (lStreamLen >= x_lMaxLen)
                           throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage));

			if (m_rgchBuf == null || m_rgchBuf.Length < lStreamLen)
				m_rgchBuf = new char[lStreamLen];

			if (m_stream.Position != 0)
				m_stream.Seek(0, SeekOrigin.Begin);

			m_stream.Read(m_rgchBuf, 0, (int)lStreamLen);
			m_stream = null;
			m_lCurLen = lStreamLen;
			m_state = SqlBytesCharsState.Buffer;

			AssertValid();
        }

		private void SetBuffer(char[] buffer) {
			m_rgchBuf = buffer;
			m_lCurLen = (m_rgchBuf == null) ? x_lNull : (long)m_rgchBuf.Length;
			m_stream = null;
			m_state = (m_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer;

			AssertValid();
		}

		// --------------------------------------------------------------
		// 		XML Serialization
		// --------------------------------------------------------------


		XmlSchema IXmlSerializable.GetSchema() { 
			return null; 
		}
		
		void IXmlSerializable.ReadXml(XmlReader r) {
			char[] value = null;
			
 			string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace);
 			
			if (isNull != null && XmlConvert.ToBoolean(isNull)) {
                // VSTFDevDiv# 479603 - SqlTypes read null value infinitely and never read the next value. Fix - Read the next value.
                r.ReadElementString();
                SetNull();
			}
			else {
				value = r.ReadElementString().ToCharArray();
				SetBuffer(value);
			}
		}

		void IXmlSerializable.WriteXml(XmlWriter writer) {
			if (IsNull) {
				writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
			}
			else {
				char[] value = this.Buffer;
				writer.WriteString(new String(value, 0, (int)(this.Length)));
			}
		}

		public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) {
			return new XmlQualifiedName("string", XmlSchema.Namespace);
		}

		// --------------------------------------------------------------
		// 		Serialization using ISerializable
		// --------------------------------------------------------------

		// State information is not saved. The current state is converted to Buffer and only the underlying
		// array is serialized, except for Null, in which case this state is kept.
		[SecurityPermissionAttribute(SecurityAction.LinkDemand,SerializationFormatter=true)]
		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
			switch (m_state)
				{
				case SqlBytesCharsState.Null:
					info.AddValue("IsNull", true);
					break;

				case SqlBytesCharsState.Buffer:
					info.AddValue("IsNull", false);
					info.AddValue("data", m_rgchBuf);
					break;

				case SqlBytesCharsState.Stream:
					CopyStreamToBuffer();
					goto case SqlBytesCharsState.Buffer;

				default:
					Debug.Assert(false);
					goto case SqlBytesCharsState.Null;
				}
			}

		// --------------------------------------------------------------
		//	  Static fields, properties
		// --------------------------------------------------------------

		// Get a Null instance. 
		// Since SqlChars is mutable, have to be property and create a new one each time.
		public static SqlChars Null {
			get	{
				return new SqlChars((char[])null);
			}
		}
	} // class SqlChars

	// StreamOnSqlChars is a stream build on top of SqlChars, and
	// provides the Stream interface. The purpose is to help users
	// to read/write SqlChars object. 
	internal sealed class StreamOnSqlChars : SqlStreamChars
		{
		// --------------------------------------------------------------
		//	  Data members
		// --------------------------------------------------------------

		private SqlChars	m_sqlchars;		// the SqlChars object 
		private long		m_lPosition;

		// --------------------------------------------------------------
		//	  Constructor(s)
		// --------------------------------------------------------------

		internal StreamOnSqlChars(SqlChars s) {
			m_sqlchars = s;
			m_lPosition = 0;
        }

		// --------------------------------------------------------------
		//	  Public properties
		// --------------------------------------------------------------

		public override bool IsNull	{
			get	{
    			return m_sqlchars == null || m_sqlchars.IsNull;
            }
        }

		// Always can read/write/seek, unless sb is null, 
		// which means the stream has been closed.
		public override bool CanRead {
            get {
                return m_sqlchars != null && !m_sqlchars.IsNull;
            }
        }

		public override bool CanSeek {
			get	{
                return m_sqlchars != null;
            }
        }

		public override bool CanWrite {
			get {
				return m_sqlchars != null && (!m_sqlchars.IsNull || m_sqlchars.m_rgchBuf != null);
            }
        }

		public override long Length	{
			get	{
				CheckIfStreamClosed("get_Length");
				return m_sqlchars.Length;
            }
        }

		public override long Position {
			get	{
				CheckIfStreamClosed("get_Position");
				return m_lPosition;
            }
			set	{
				CheckIfStreamClosed("set_Position");
				if (value < 0 || value > m_sqlchars.Length)
					throw new ArgumentOutOfRangeException("value");
				else
					m_lPosition = value;
            }
        }

		// --------------------------------------------------------------
		//	  Public methods
		// --------------------------------------------------------------

		public override long Seek(long offset, SeekOrigin origin) {
			CheckIfStreamClosed("Seek");

			long lPosition = 0;

			switch(origin) {
				case SeekOrigin.Begin:
					if (offset < 0 || offset > m_sqlchars.Length)
						throw ADP.ArgumentOutOfRange("offset");
					m_lPosition = offset;
					break;
					
				case SeekOrigin.Current:
					lPosition = m_lPosition + offset;
					if (lPosition < 0 || lPosition > m_sqlchars.Length)
						throw ADP.ArgumentOutOfRange("offset");
					m_lPosition = lPosition;
					break;
					
				case SeekOrigin.End:
					lPosition = m_sqlchars.Length + offset;
					if (lPosition < 0 || lPosition > m_sqlchars.Length)
						throw ADP.ArgumentOutOfRange("offset");
					m_lPosition = lPosition;
					break;
					
				default:
                    throw ADP.ArgumentOutOfRange("offset");;
            }

			return m_lPosition;
        }

		// The Read/Write/Readchar/Writechar simply delegates to SqlChars
		public override int Read(char[] buffer, int offset, int count) {
			CheckIfStreamClosed("Read");

			if (buffer==null)
				throw new ArgumentNullException("buffer");
			if (offset < 0 || offset > buffer.Length)
				throw new ArgumentOutOfRangeException("offset");
			if (count < 0 || count > buffer.Length - offset)
				throw new ArgumentOutOfRangeException("count");

			int icharsRead = (int)m_sqlchars.Read(m_lPosition, buffer, offset, count);
			m_lPosition += icharsRead;

			return icharsRead;
        }

		public override void Write(char[] buffer, int offset, int count) {
			CheckIfStreamClosed("Write");

			if (buffer==null)
				throw new ArgumentNullException("buffer");
			if (offset < 0 || offset > buffer.Length)
				throw new ArgumentOutOfRangeException("offset");
			if (count < 0 || count > buffer.Length - offset)
				throw new ArgumentOutOfRangeException("count");

			m_sqlchars.Write(m_lPosition, buffer, offset, count);
			m_lPosition += count;
        }

		public override int ReadChar() {
    		CheckIfStreamClosed("ReadChar");

			// If at the end of stream, return -1, rather than call SqlChars.Readchar,
			// which will throw exception. This is the behavior for Stream.
			//
			if (m_lPosition >= m_sqlchars.Length)
				return -1;

			int ret = m_sqlchars[m_lPosition];
			m_lPosition ++;
			return ret;
        }

		public override void WriteChar(char value) {
			CheckIfStreamClosed("WriteChar");

			m_sqlchars[m_lPosition] = value;
			m_lPosition ++;
        }

		public override void SetLength(long value) {
			CheckIfStreamClosed("SetLength");

			m_sqlchars.SetLength(value);
			if (m_lPosition > value)
				m_lPosition = value;
        }

		// Flush is a no-op if underlying SqlChars is not a stream on SqlChars
		public override void Flush() {
			if (m_sqlchars.FStream())
				m_sqlchars.m_stream.Flush();
        }

        protected override void Dispose(bool disposing) {           
			// When m_sqlchars is null, it means the stream has been closed, and
			// any opearation in the future should fail.
			// This is the only case that m_sqlchars is null.
			m_sqlchars = null;
        }

		// --------------------------------------------------------------
		//	  Private utility functions
		// --------------------------------------------------------------

		private bool FClosed() {
			return m_sqlchars == null;
        }

        private void CheckIfStreamClosed(string methodname)	{
			if (FClosed())
                throw ADP.StreamClosed(methodname);
        }
    } // class StreamOnSqlChars
} // namespace System.Data.SqlTypes